using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace A4G.Utils.Xml
{
	public static class XmlSerializationHelper<T>
	{
		private static readonly XmlSerializer _serializer = new XmlSerializer(typeof(T));

		public static void SerializeToFile(string fileName, T objectToSerialize)
		{
			XmlTextWriter writer = new XmlTextWriter(fileName, Encoding.Default);
			writer.Formatting = Formatting.Indented;

			try
			{
				_serializer.Serialize(writer, objectToSerialize);
			}
			finally
			{
				writer.Close();
			}
		}

		public static T DeserializeFromFile(string fileName)
		{
			XmlTextReader reader = new XmlTextReader(fileName);

			try
			{
				T serializedObject = (T) _serializer.Deserialize(reader);
				return serializedObject;
			}
			finally
			{
				reader.Close();
			}
		}

		public static void SerializeToStream(Stream destination, T objectToSerialize)
		{
			_serializer.Serialize(destination, objectToSerialize);
		}

		public static T DeserializeFromStream(Stream source)
		{
			return (T)_serializer.Deserialize(source);
		}
	}
}
